<!--
 * @Date: 2025-01-02 16:18:28
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2025-01-16 17:43:06
 * @Description: 表单页面设计
-->
<template>
  <VFormDesigner
    ref="designerRef"
    :="designerAttrs"
    class="fp-designer-container"
  >
  </VFormDesigner>
</template>

<script setup>
import { nextTick, reactive, ref } from 'vue';
import { useUserStore } from '@/stores/modules';

import XEUtils from 'xe-utils';

import { defAxios } from '@/utils/http';
import { slotFull } from '@fp/slots';
import { EnumsDataPools } from '@/enums';

const emits = defineEmits([ 'loaded' ])

// 属性定义
const props = defineProps({
  formJson: { type: [String, Object], default: '' }
})

// 设计器组件的Ref对象
const designerRef = ref()
// 设计器组件的配置
const designerAttrs = reactive({
  busiConfig: {
    userInfo: useUserStore().userInfo,
    dataHouse: {},
  },
  enumsConfig: {
    dataPools: EnumsDataPools
  },
  slotsConfig: {
    dataPools: slotFull
  },
  axiosConfig: {
    request: defAxios,
  },
  designerConfig: {
    resetFormJson: true
  }
})
const designerState = reactive({
  loading: false
})

// 不是表单类型的组件类型
const noFormTypes = [
  'data-table',
  'zoning-unit-tree'
]

const designDataLoaded = () => {
  nextTick(() => {
    designerState.loading = false
    emits('loaded')
  })
}

/**
 * 获取设计数据
 */
const getDesignData = () => {
  const slotJson = []
  const formJson = designerRef.value.getFormJson()
  const formFileds = []
  const fieldWidgets = designerRef.value.getFieldWidgets()
  const containerWidgets = designerRef.value.getContainerWidgets()
  if ((fieldWidgets.length + containerWidgets.length) === 0) return null
  for (let item of fieldWidgets) {
    const { type, field } = item
    if (noFormTypes.includes(type)) continue;
    // 判断是否为插槽组件
    if (type === 'slot') {
      slotJson.push({
        id: field.id,
        key: field.key,
        value: item.name,
        label: field.options.label
      })
    } else {
      // 数据字段
      const dataField = field.options.dataField
      if (!dataField) continue;
      let fields = dataField.split('.')
      formFileds.push({
        // type,
        code: item.name,
        field:  fields[1] || '',
        tableName: fields[0] || ''
      })
    }
  }
  return {
    formJson, slotJson, formFileds
  }
}

// 监听表单配置变化，更新设计器
watch(
  () => props.formJson,
  (nv, ov) => {
    nextTick(() => {
      if (!designerRef.value) return
      designerState.loading = true
      if (XEUtils.isEmpty(nv)) {
        designerRef.value.clearDesigner()
        designDataLoaded()
      } else {
        setTimeout(() => {
          designerRef.value.setFormJson(XEUtils.clone(nv, true))
          designDataLoaded()
        }, 100)
      }
    })
  },
  { deep: true, immediate: true, once: true }
)

defineExpose({
  getDesignData
})

</script>

<style lang="scss">
.fp-designer-container {
  .form-widget-container {
    .el-tabs__header {
      background-color: #e3f1fe;
      margin-bottom: 0;
    }
  }
}
</style>